<template>
    <div class="selectAddress-page">

        <van-row class="title_address"
            type="flex"
            justify="space-around"
            align="center">
            <van-col span="2"
                class="city"
                @click="toBackPage()">
                <van-icon name="cross"
                    class="icon"
                    color="#C1C1C1" />
            </van-col>

            <van-col span="22"
                class='search'>
                <van-search v-model="addressValue"
                    id="addressInput"
                    placeholder="请输入招聘单位所在地址"
                    @search="onSearchAddress"
                    shape="round"
                    class="search_content"
                    background="#E6E6E6">
                    <template #action>
                        <div @click="onSearchAddress">搜索</div>
                    </template>
                </van-search>
            </van-col>
        </van-row>

        <!--  滚动切换    -->
        <van-tabs v-model="active"
            class="city_town"
            swipeable
            color="#1989fa">
            <van-tab v-for=" item in addressType"
                :title="item.title"
                :key="item.id"
                class="cityOrTown">

                <div class="addressContent">

                    <current-and-history :prePage="prePage"
                        :jobTypeId="jobTypeId"
                        :currentCity="currentCity"
                        :currentStreet="currentStreet"
                        :historyAddress="historyAddress"></current-and-history>

                    <div v-show="active === 0"
                        class="cityContent">
                        <div class="cityList">
                            <div class="selectCity">选择城市</div>

                            <van-index-bar v-if="cityArr.length"
                                :index-list="indexArr">
                                <div v-for="(item, index) in cityArr"
                                    :key="index">
                                    <van-index-anchor :index="item.initial" />
                                    <van-cell v-for="(ch, idx) in item.cityList"
                                        :title="ch.full_name"
                                        :key="ch.encode"
                                        @click="handleCurrentCity(ch)" />
                                </div>
                            </van-index-bar>
                            <van-empty v-else
                                image="network"
                                description="正在加载中" />
                        </div>
                        <div class="city_bottom">到底部啦~~~</div>
                        <nut-backtop :bottom="16"
                            :right="6"></nut-backtop>
                    </div>

                    <div v-show="active === 1"
                        class="townContent">
                        <div class="all_town">
                            <div>所有区域</div>
                        </div>
                        <div class="choose_town">
                            <van-cascader title="所有区域"
                                v-model="townValue"
                                :closeable="false"
                                :options="townOptions"
                                @finish="onFinish"
                                @change="onChangeArea" />
                        </div>
                    </div>
                </div>
            </van-tab>
        </van-tabs>

    </div>
</template>

<script>
import CurrentAndHistory from '../../components/CurrentAndHistory'
import provinceList from '../../constants/provinceList'
import {Toast, Dialog} from 'vant'
import constant from '../../utils/constant'
import {cityFilter, storageHistoryLocation} from '../../utils/index'

// 生成所需要的数据
const provinceArr = provinceList.map(item => ({
  text: item.name,
  value: item.id,
  children: []
}))

export default {
  name: 'selectAddress',
  components: {
    CurrentAndHistory
  },
  data() {
    return {
      cityId: '', // 定位的城市
      cityName: '',
      adcode: '',
      township: '',
      currentCityName: '', // 当前选择的城市
      addressValue: '',
      currentCity: null,
      currentStreet: null,

      historyAddress: [],
      active: 0,
      addressType: [
        {
          id: '0',
          title: '城市'
        },
        {
          id: '1',
          title: '乡镇'
        }
      ],
      cityArr: [],
      indexArr: [],
      townValue: '',
      townOptions: provinceArr,
      full_town_address: '',

      // 地址搜索自动联想以及地址搜索组件
      autoCompleteComponent: undefined,
      placeSearchComponent: undefined,

      prePage: 'home', // 来源页(默认 home 页)
      jobTypeId: ''
    }
  },

  mounted() {
    window.addEventListener('setItem', e => {
      if (e.key === constant.STORAGE_LOCATION_CITY_ID) {
        this.cityId = localStorage.getItem(constant.STORAGE_LOCATION_CITY_ID)
      }
      if (e.key === constant.STORAGE_LOCATION_CITY_NAME) {
        this.cityName = localStorage.getItem(constant.STORAGE_LOCATION_CITY_NAME)
      }
      if (e.key === constant.STORAGE_LOCATION_AD_CODE) {
        this.adcode = localStorage.getItem(constant.STORAGE_LOCATION_AD_CODE)
      }
      if (e.key === constant.STORAGE_LOCATION_TOWNSHIP) {
        this.township = localStorage.getItem(constant.STORAGE_LOCATION_TOWNSHIP)
      }
      if (e.key === constant.STORAGE_HISTORY_LOCATION) {
        this.historyAddress = JSON.parse(localStorage.getItem(constant.STORAGE_HISTORY_LOCATION))
      }

      if (e.key === constant.STORAGE_CURRENT_ADDRESS) {
        if (localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS)) {
          this.currentCityName = JSON.parse(localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS)).name
          // 修改城市
          this.autoCompleteComponent.setCity(this.currentCityName)
        }
      }
    })
  },

  watch: {
    cityId(val) {
      if (this.cityId && this.cityName) {
        let address = {
          id: this.cityId,
          name: this.cityName
        }
        this.currentCity = address
      }
    },
    township(val) {
      if (this.adcode && this.township) {
        this.$api.others
          .reqAllAddress(this.adcode)
          .then(res => {
            if (res.code === 200 && res.data) {
              for (let item of res.data) {
                if (item.name.indexOf(this.township) > -1) {
                  let address = {
                    id: item.id,
                    name: item.name
                  }
                  this.currentStreet = address
                  break
                }
              }
            }
          })
          .catch(error => {
            // Toast('服务器连接失败!')
            //console.log(error)
          })
      }
    }
  },
  async created() {
    const res = await this.$api.others.reqGroupCity()
    if (res.code === 200) {
      this.cityArr = res.data
      this.indexArr = res.data.map(item => item.initial)
    }

    this.cityId = localStorage.getItem(constant.STORAGE_LOCATION_CITY_ID)
    this.cityName = localStorage.getItem(constant.STORAGE_LOCATION_CITY_NAME)
    this.adcode = localStorage.getItem(constant.STORAGE_LOCATION_AD_CODE)
    this.township = localStorage.getItem(constant.STORAGE_LOCATION_TOWNSHIP)
    if (localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS)) {
      this.currentCityName = JSON.parse(localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS)).name
    }

    console.log('this.currentCityName', this.currentCityName)
    this.historyAddress = JSON.parse(localStorage.getItem(constant.STORAGE_HISTORY_LOCATION))

    // 初始化地址搜索工具
    this.mapSearchInit()
  },

  methods: {
    handleCurrentCity(city) {
      const self = this
      let address = {
        type: '1', // 1为城市；2为街道
        id: city.encode,
        name: city.full_name
      }

      //正向地理编码
      AMap.plugin('AMap.Geocoder', function () {
        let geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: '全国'
        })

        geocoder.getLocation(city.full_name, function (status, data) {
          if (status === 'complete' && data.info === 'OK') {
            // result为对应的地理位置详细信息
            console.log('城市坐标查询', data)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, data.geocodes[0].location.lat)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, data.geocodes[0].location.lng)
            // 当前城市
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, city.full_name)
          }
          self.$router.push({
            name: self.prePage,
            // query: {id: self.jobTypeId}
          })
        })
      })
    },

    handleCurrentStreet(cityId, cityName, streetId, streetName) {
      // TODO: 这里街道还是按城市来处理
      const self = this
      let address = {
        type: '1', // 1为城市；2为街道
        id: cityId,
        name: cityName
      }

      //正向地理编码
      AMap.plugin('AMap.Geocoder', function () {
        let geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: cityName
        })

        geocoder.getLocation(streetName, function (status, data) {
          if (status === 'complete' && data.info === 'OK') {
            // result为对应的地理位置详细信息
            console.log('城市坐标查询', data)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, data.geocodes[0].location.lat)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, data.geocodes[0].location.lng)
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
            self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, streetName)
          }

          let street = {
            type: '2', // 1为城市；2为街道
            cityId: cityId,
            cityName: cityName,
            id: streetId,
            name: streetName
          }
          storageHistoryLocation(street)

          self.townValue = ''

          self.$router.push({
            name: self.prePage,
            // query: {id: self.jobTypeId}
          })
        })
      })
    },

    toReset() {
      Toast.success({
        message: '已重置',
        duration: 160
      })
      // 重置
    },

    toBackPage() {
      // 没有选择，清空当前位置信息重新定位
      localStorage.removeItem(constant.STORAGE_CURRENT_ADDRESS)
      localStorage.removeItem(constant.STORAGE_CURRENT_LAT)
      localStorage.removeItem(constant.STORAGE_CURRENT_LNG)
      localStorage.removeItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)

      this.$router.push({
        name: this.prePage,
        // query: {id: this.jobTypeId}
      })
    },

    async _getAllTownArr(id, idx, selectedOptionObj) {
      // 从0开始，想要几级就小于几
      if (idx < 3) {
        const res = await this.$api.others.reqAllAddress(id)
        if (res.code === 200) {
          // 请求成功, 生成所需要的children
          const arr = res.data.map(item => {
            let obj
            if (idx === 2) {
              // 最后一级，则不生成children数组
              obj = {
                text: item.name,
                value: item.id
              }
            } else {
              obj = {
                text: item.name,
                value: item.id,
                children: []
              }
            }
            return obj
          })
          selectedOptionObj.children = arr
        }
      }
    },

    onChangeArea({value, selectedOptions, tabIndex}) {
      this._getAllTownArr(value, tabIndex, selectedOptions[tabIndex])
    },

    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({selectedOptions}) {
      this.full_town_address = selectedOptions.map(option => option.text).join('')
      Dialog.confirm({
        message: `你选择地址是：${this.full_town_address}`,
        messageAlign: 'left'
      })
        .then(() => {
          // on confirm
          let cityId = selectedOptions[1].value
          let cityName = selectedOptions[1].text
          let streetId = selectedOptions[3].value
          let streetName = selectedOptions[3].text
          this.handleCurrentStreet(cityId, cityName, streetId, streetName)
        })
        .catch(() => {
          // on cancel
        })
    },

    /** 初始化地址搜索工具 */
    mapSearchInit() {
      const self = this
      // 绑定自动提示
      AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
        var autoOptions = {
          input: 'addressInput', //值为界面上input空间id
          city: self.currentCityName
        }
        var autoCompleteComponent = new AMap.Autocomplete(autoOptions)
        // 注册监听Autocomplete选中项
        AMap.event.addListener(autoCompleteComponent, 'select', function (data) {
          console.log('注册监听Autocomplete选中项', data)
          self.addressValue = data.poi.name

          // 如果选择的是城市，则没有 location 数据
          if (data.poi.location) {
            let lat = data.poi.location.lat // 纬度
            let lng = data.poi.location.lng // 经度

            //逆向地理编码
            AMap.plugin('AMap.Geocoder', function () {
              let geocoder = new AMap.Geocoder({})
              let lnglat = [lng, lat]
              geocoder.getAddress(lnglat, function (status, geoData) {
                if (status === 'complete' && geoData.info === 'OK') {
                  // result为对应的地理位置详细信息
                  console.log('获取选中地址的地理位置', geoData)
                  let cityCode = geoData.regeocode.addressComponent.citycode
                  let city = cityFilter(cityCode)
                  if (city) {
                    let address = {
                      type: '1', // 1为城市；2为街道
                      id: city.id,
                      name: city.name
                    }

                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, lat)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, lng)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, self.addressValue)
                  }
                }

                self.$router.push({
                  name: self.prePage,
                  // query: {id: self.jobTypeId}
                })
              })
            })
          } else {
            //正向地理编码
            AMap.plugin('AMap.Geocoder', function () {
              let geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: '全国'
              })

              geocoder.getLocation(data.poi.name, function (status, geoData) {
                if (status === 'complete' && geoData.info === 'OK') {
                  // result为对应的地理位置详细信息
                  console.log('获取选中地址的地理位置', geoData)

                  let cityCode = geoData.geocodes[0].addressComponent.citycode
                  let city = cityFilter(cityCode)
                  if (city) {
                    let address = {
                      type: '1', // 1为城市；2为街道
                      id: city.id,
                      name: city.name
                    }

                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, geoData.geocodes[0].location.lat)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, geoData.geocodes[0].location.lng)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, self.addressValue)
                  }
                }

                self.$router.push({
                  name: self.prePage,
                  // query: {id: self.jobTypeId}
                })
              })
            })
          }
        })

        self.autoCompleteComponent = autoCompleteComponent
        // 注册placeSearch组件
        self.placeSearchComponent = new AMap.PlaceSearch({
          // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
          city: self.currentCityName,
          extensions: 'all'
        })
      })
    },

    /** 关键词搜索 */
    onSearchAddress() {
      console.log('addressValue', this.addressValue)
      this.placeSearchComponent.search(this.addressValue, function (status, result) {
        // 查询成功时，result即对应匹配的POI信息
        console.log(status)
        console.log(result)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.selectAddress-page {
  width: 100%;
  box-sizing: border-box;
  .title_address {
    height: 46px;
    line-height: 46px;
    text-align: center;
    background-color: #e6e6e6;
    .city {
      font-size: 20px;
      height: 34px;
      .icon {
        font-size: 28px;
      }
    }
    .search {
      /deep/ .van-search {
        padding: 0;
      }
    }
  }
  .city_town {
    .cityOrTown {
      border-top: 1px solid #e6e6e6;
      .addressContent {
        .cityContent {
          .cityList {
            .selectCity {
              background-color: #ffffff;
              height: 40px;
              line-height: 40px;
              padding-left: 16px;
              font-size: 13px;
              font-weight: bold;
            }
            .van-index-bar {
              /deep/ .van-index-bar__sidebar {
                z-index: 100;
                top: 355px;
                .van-index-bar__index {
                  line-height: 0.6rem;
                  padding: 0 0.10667rem 0 0.42667rem;
                }
              }
            }
          }
          .city_bottom {
            margin-top: 8px;
            height: 20px;
            line-height: 20px;
            font-size: 8px;
            text-align: center;
            padding-bottom: 2px;
          }
        }
        .townContent {
          .all_town {
            background-color: #ffffff;
            height: 40px;
            padding-left: 16px;
            font-size: 13px;
            font-weight: bold;
            border-bottom: 1px solid #e6e6e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
          .choose_town {
            /deep/ .van-cascader {
              font-size: 13px !important;
              .van-cascader__header {
                display: none;
              }
              .van-cascader__tabs {
                .van-tabs__wrap--scrollable {
                  box-sizing: border-box;
                  .van-tabs__nav--complete {
                    box-sizing: border-box;
                    height: 36px;
                    line-height: 36px;
                    padding-left: 16px;
                    padding-bottom: 0;
                    .van-cascader__tab {
                      padding: 0 3px 0 0;
                      font-size: 14px;
                      color: #fc5531;
                    }
                    .van-cascader__tab--unselected {
                      color: #969799;
                    }
                  }
                  .van-tabs__line {
                    top: 32px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
